function creardatatablemerc() {

	var checkFmt = function(cell, row, col, data){
        var checked =data;
        if (checked == 'true' || checked == true) {
            cell.innerHTML = '<div align="center"><input type="checkbox" name="ignorame" checked="checked" ></input></div>';
        } else {
            cell.innerHTML = '<div align="center"><input type="checkbox" name="ignorame" ></input></div>';
        }
    };
    
    var eliminarFormatter = function(cell, row, col, data) {
		cell.innerHTML = '<div style="text-align: center"><input type="image" src="'
				+ Z.zuictx
				+ '/trash.gif" value="Eliminar" size="21,21" style="width:21px;height:21px" border="0" alt="Eliminar" onclick="return false;"/></div>';
	};
    
	var myColumnDefs = [ {
		key : "id",
		label : "ID"
	},{
		key : "desc",
		label : "NOMBRE COMUN"
	}, {
		key : "scien",
		label : "NOMBRE CIENTIFICO"
	
	},{
		key : "id",
		label : "ELIMINAR",
		formatter:eliminarFormatter
	}];

	try {
		var config = {};
		config.URL = Context.Mercancias;
		config.FIELDS = [ "act","id", "desc", "scien","username", "modificado", "nuevo", "eliminado" ];
		config.COLUMNS = myColumnDefs;
		config.DATATABLE_DIV = "datatablem";
		config.PAGINATOR_DIV = "paginatorm";
		config.TOTAL_REGISTROS_DIV = "totalregistrosm";
		config.ROW_PER_PAGE = 10;

		Context.tablem = new Z.Table(config);
		myDataTablem = Context.tablem.getDatatable();
		
		myDataTablem.subscribe("checkboxClickEvent", function(oArgs) {
			var target = oArgs.target;
			var record = this.getRecord(target);
	        record.setData("modificado", true);
		});
		
		myDataTablem.subscribe("buttonClickEvent", function(oArgs) {

			var target = oArgs.target;
			var record = this.getRecord(target);
			 if (target.value == "Eliminar") {

				 myDataTablem.eliminarRegistro(record);
				// this.deleteRow(record);
			} else {
				alert("buttonClickEvent value desconocido: " + target.value);
			}
			return false;
		});
		
	} catch (e) {
		alert(e);
	}
	
	myDataTablem.insertarRegistro = function(oData) {
		try {
			var dtbl = Context.tablem.getDatatable();
			oData['nuevo'] = true;
			oData['modificado'] = false;
			oData['eliminado'] = false;
			dtbl.addRow(oData, 0);
			myDataTablem.render();
			Context.dialog1.hide();
		} catch (x) {
			alert("insertarRegistro: " + x.description+ x.message);
			return false;
		}
	};	
	
	myDataTablem.insertar = function(rows){
        try {
            if (Y.lang.isArray(rows)) {
                for (var j = 0; j < rows.length; j++) {
                    var m = rows[j];
                    try {
                        var oData = {};
                        
                        oData['id'] = m.id;
                        oData['desc'] = m.desc;
                        oData['scien'] = m.scien;
                        oData['act'] = m.act;
                        oData['username'] = m.username;
                        oData['modificado'] = false;
                        oData['nuevo'] = false;
                        oData['eliminado'] = false;
                        myDataTablem.addRow(oData, myDataTablem.getRecordSet().getLength());
                        myDataTablem.render();
                    } catch (e) {
                        alert("insertar:" + e.description+" "+x.message);
                    }
                }
                
            }
        } catch (x) {
            alert("insertar: " + x.description +" "+x.message);
            return false;
        }
    };
	
    

	    myDataTablem.eliminarRegistro = function(record) {

			var ejecuta = true;
	
			if (record.getData("nuevo") == true
					|| record.getData("nuevo") == 'true') {
				myDataTablem.deleteRow(record);
				ejecuta = false;
			}
			if (record.getData("eliminado") == true) {
				ejecuta = false;
				return;
			}
			if (ejecuta) {
				try {
					Context.eliminarDlg = new Y.widget.SimpleDialog("eliminarDlg",
							{
								width : "17em",
								fixedcenter : true,
								modal : true,
								visible : false,
								draggable : false
							});
	
					Context.eliminarDlg.setHeader("Confirmaci&oacute;n");
					Context.eliminarDlg.setBody("¿Desea borrar esta mercancia?");
					Context.eliminarDlg.cfg.setProperty("icon",
							Y.widget.SimpleDialog.ICON_WARN);
	
					var handleYes = function() {
						try {
							record.setData("eliminado", true);
							myDataTablem.render();
							this.hide();
						} catch (e) {
							alert("eliminar handleYes: " + e + e.description);
						}
					};
					var handleNo = function() {
						this.hide();
					};
					var myButtons = [ {
						text : "Aceptar",
						handler : handleYes
					}, {
						text : "Cancel",
						handler : handleNo,
						isDefault : true
					} ];
	
					Context.eliminarDlg.cfg.queueProperty("buttons", myButtons);
					Context.eliminarDlg.render(document.body);
					Context.eliminarDlg.show();
	
				} catch (e) {
					alert("eliminar: " + e + e.description);
				}
			}
	};
	
}

function guardarMercancia() {
	try {
		
		var f = document.getElementById("MercanciaForm");
		f.elements["jsonrecords"].value = Context.tablem.getJsonRecords();

		var callback = new Z.JsonCall();
		callback.exito = function(data) {
			Z.mercAgregarButton.set("disabled", true);
			Z.mercGuardarButton.set("disabled", true);
			Context.table.update();
			Context.tablem.clear();
		};
		callback.fallo = function(messages) {
			alert("error")
		};
		
		Z.ShowWait();
		Y.util.Connect.setForm(f);
		var request = Y.util.Connect.asyncRequest('POST', Context.GuardarMercancia, callback);
		
	} catch (e) {
		alert("guardar: " + e + e.description);
	}
};



function insertarMercancia(){
	
	var f = document.getElementById("mercform");
	var key = f.elements['mercancias'].value;
	
	
	var g = document.getElementById("mercUserForm");
	
	var mercancias = [];
	var s = f.elements['mercancias'];
	for (var i = 0; i < s.options.length; i++) {
        if (s.options[i].selected == true) {
            var id = s.options[i].value;
            mercancias.push(id);
        }
    }
	
	var selectedRows = myDataTable.getSelectedRows();
	var record = myDataTable.getRecord(selectedRows[0]);
	 
	g.elements['idMercancia'].value = mercancias;
	g.elements['username'].value = record.getData('username');
	 
	 var callback = new Z.JsonCall();
		callback.exito = function(data) {
			
			if (Y.lang.isArray(data.ResultSet.Result)) {
             for (var j = 0; j < data.ResultSet.Result.length; j++) {
                var m = data.ResultSet.Result[j];
                 
                var oData = {};
                oData['id'] = m.id;
                oData['desc'] = m.desc;
                oData['scien'] = m.scien;
                oData['username'] = record.getData('username');
                myDataTablem.insertarRegistro(oData);
                
				var f = document.getElementById("mercform");
		    	Z.ClearForm(f); 
		    	Context.dialog2.hide();
             }
			}
			
			
		};
		callback.fallo = function(messages) {
			alert("error")
		};
		
		Z.ShowWait();
		Y.util.Connect.setForm(g);
		var request = Y.util.Connect.asyncRequest('POST', Context.MercanciasPorId, callback);
	
	
	
}



function loadMercancias(){
	
	try {
		var f = document.getElementById("mercform");
		var val = f.elements['idTipoCertificado'].value;
		if(val == ''|| val == undefined){
			return
		}
		var selectedRows = myDataTable.getSelectedRows();
		var record = myDataTable.getRecord(selectedRows[0]);
		f.elements['username'].value = record.getData('username');
		
		var callback = new Z.JsonCall();
		callback.exito = function(data) {
			
			if (Y.lang.isArray(data.ResultSet.Result)) {
                for (var j = 0; j < data.ResultSet.Result.length; j++) {
                   var m = data.ResultSet.Result[j];
                    // Dom.get("SPSExDocIssuerSPSPartyName").innerHTML =
					// m.SPSExDocIssuerSPSPartyName;
        			
                   var opt = document.createElement("option");
     			   opt.value= m.id;
     			   opt.innerHTML = m.desc + ' - '+ m.scien; // whatever property
															// it has

     			   // then append it to the select element
     			   f.elements['mercancias'].appendChild(opt);
                }
			}
			
			
		};
		callback.fallo = function(messages) {
			alert("error")
		};
		
		Z.ShowWait();
		Y.util.Connect.setForm(f);
		var request = Y.util.Connect.asyncRequest('POST', Context.Mercancias, callback);
		
		
		
		// Context.tablem.update();
	} catch (e) {
		alert("mercancia: " + e + e.description);
	}
	
}

function creardialogoMercancia() {
	Context.dialog2 = new Y.widget.Dialog("dialog2", {
		width : "30em",
		fixedcenter : true,
		visible : false,
		constraintoviewport : true,
		modal : true,
		zindex : 5,
		buttons : [ {
			text : "Aceptar",
			handler : function() {
				
				
				insertarMercancia();
			},
			isDefault : true
		}, {
			text : "Cancelar",
			handler : function() {
				Context.dialog2.hide();
				var f = document.getElementById("mercform");
		    	Z.ClearForm(f); 
		    	Z.DeleteMulti(f.elements['mercancias']);
			}
		} ]
	});
	var kw = new Y.util.KeyListener(document, {
		keys : 27
	}, {
		fn : Context.dialog2.hide,
		scope : Context.dialog2,
		correctScope : true
	});
	kw.enable();
	Context.dialog2.render(document.body);
}



Y.util.Event.onDOMReady(function() {
	try {
		creardatatablemerc();
		creardialogoMercancia();
		// Context.tablem.update();
	} catch (e) {
		alert(e);
	}
});

